package tcu.iot.gasmanage.service;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tcu.iot.gasmanage.common.DownloadResult;
import tcu.iot.gasmanage.common.Result;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;

@Service
@Transactional
public class DownloadService {

    //前端检索是否需要更新软件
    public DownloadResult UpdateInfo() {
        return DownloadResult.update("/Users/litengyue/Projects/JavaProjects/tcu.iot/src/main/resources/templates/app-debug.apk", "3.5.1", 8);
    }

    public Result Download(HttpServletRequest request, HttpServletResponse response) {
        //下载的文件路径
        String filePath = "/Users/litengyue/Projects/JavaProjects/tcu.iot/src/main/resources/templates/app-debug.apk";
        //下载后的文件名
        String fileName = "app-debug.apk";

        //使用流的形式下载文件
        try {
            //加载文件
            File file = new File(filePath);
            InputStream is = new BufferedInputStream(new FileInputStream(file));
            byte[] buffer = new byte[is.available()];
            is.read(buffer);
            is.close();
            // 清空response
            response.reset();
            // 设置response的Header
            response.addHeader("Content-Disposition", "attachment;filename=" + "app-debug.apk");
            response.addHeader("Content-Length", "" + file.length());
            OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");
            toClient.write(buffer);
            toClient.flush();
            toClient.close();

            return Result.ok("true", 200, "成功", "下载成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.failed("false", 400, "失败");
        }
    }
}
